<template>
  <div class="announcement-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>公告信息</h2>
          <p>查看系统通知、停车场公告和活动信息</p>
        </div>
        <div class="page-actions">
          <el-input 
            v-model="searchTitle" 
            placeholder="搜索公告标题" 
            clearable
            @clear="fetchAnnouncements"
            @keyup.enter="fetchAnnouncements"
            style="width: 200px;"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchAnnouncements"></el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-card>
    
    <el-row :gutter="20">
      <!-- 左侧分类 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="4">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>公告分类</span>
            </div>
          </template>
          
          <el-menu
            :default-active="activeCategory.toString()"
            class="category-menu"
            @select="handleCategorySelect"
          >
            <el-menu-item index="0">
              <el-icon><Document /></el-icon>
              <span>全部公告</span>
            </el-menu-item>
            <el-menu-item 
              v-for="category in categories" 
              :key="category.id" 
              :index="category.id.toString()"
            >
              <el-icon>
                <component :is="getCategoryIcon(category.id)"></component>
              </el-icon>
              <span>{{ category.name }}</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <!-- 右侧列表 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="20">
        <el-card v-if="loading" v-loading="loading" class="list-card">
          <div style="height: 400px;"></div>
        </el-card>
        <template v-else>
          <div class="announcement-list">
            <el-empty v-if="announcements.length === 0" description="暂无公告"></el-empty>
            <el-card 
              v-for="item in announcements" 
              :key="item.id" 
              class="announcement-item"
              :class="{ 'announcement-top': item.isTop === 1 }"
              @click="showDetail(item.id)"
            >
              <div class="announcement-header">
                <h3 class="announcement-title">
                  <el-tag v-if="item.isTop === 1" type="danger" size="small" class="top-tag">置顶</el-tag>
                  {{ item.title }}
                </h3>
                <div class="announcement-meta">
                  <el-tag size="small" :type="getCategoryTagType(item.categoryId)">
                    {{ item.categoryName }}
                  </el-tag>
                  <span class="publisher">发布人: {{ item.publisherName }}</span>
                  <span class="date">{{ formatDate(item.createdAt) }}</span>
                </div>
              </div>
              <div class="announcement-content">
                {{ truncateText(item.content, 150) }}
              </div>
              <div class="announcement-footer">
                <span class="read-count">
                  <el-icon><View /></el-icon> 阅读({{ item.readCount }})
                </span>
                <el-button type="primary" link @click.stop="showDetail(item.id)">查看详情</el-button>
              </div>
            </el-card>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </template>
      </el-col>
    </el-row>
    
    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="detailTitle"
      :fullscreen="false"
      destroy-on-close
    >
      <div v-loading="detailLoading" class="detail-container">
        <template v-if="announcementDetail">
          <div class="detail-header">
            <div class="detail-meta">
              <el-tag size="small" :type="getCategoryTagType(announcementDetail.categoryId)">
                {{ announcementDetail.categoryName }}
              </el-tag>
              <span class="detail-publisher">发布人: {{ announcementDetail.publisherName }}</span>
              <span class="detail-date">{{ formatDate(announcementDetail.createdAt) }}</span>
            </div>
            <div class="detail-read-count">
              <el-icon><View /></el-icon> 阅读({{ announcementDetail.readCount }})
            </div>
          </div>
          <div class="detail-content">
            <p v-html="formatContent(announcementDetail.content)"></p>
          </div>
          <div class="detail-valid-time">
            <span>有效期: {{ formatDate(announcementDetail.startTime) }} 至 {{ formatDate(announcementDetail.endTime) }}</span>
          </div>
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useBreakpoints } from '@vueuse/core'
import { Search, Document, Bell, InfoFilled, Promotion, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getAnnouncementList, getAnnouncementDetail, getAnnouncementCategories } from '@/api/announcement'

// 响应式设计
const breakpoints = useBreakpoints({
  mobile: 768,
  tablet: 992,
  laptop: 1200,
})
const isMobile = computed(() => breakpoints.smaller('tablet'))

// 公告列表相关
const searchTitle = ref('')
const activeCategory = ref(0)
const categories = ref([])
const announcements = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 公告详情相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const announcementDetail = ref(null)
const detailTitle = computed(() => announcementDetail.value?.title || '公告详情')

// 获取公告列表
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      title: searchTitle.value || undefined,
      categoryId: activeCategory.value > 0 ? activeCategory.value : undefined
    }
    
    const res = await getAnnouncementList(params)
    if (res.code === 200 && res.data) {
      announcements.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      announcements.value = []
      total.value = 0
      console.error('获取公告列表返回错误:', res)
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
    announcements.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取公告分类
const fetchCategories = async () => {
  try {
    const res = await getAnnouncementCategories()
    categories.value = res.data
  } catch (error) {
    ElMessage.error('获取公告分类失败')
  }
}

// 获取公告详情
const getDetail = async (id) => {
  detailLoading.value = true
  try {
    const res = await getAnnouncementDetail(id)
    announcementDetail.value = res.data
  } catch (error) {
    ElMessage.error(error.message || '获取公告详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAnnouncements()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

// 处理分类选择
const handleCategorySelect = (index) => {
  activeCategory.value = parseInt(index)
  currentPage.value = 1
  fetchAnnouncements()
}

// 显示公告详情
const showDetail = (id) => {
  announcementDetail.value = null
  detailVisible.value = true
  getDetail(id)
}

// 根据分类ID获取对应图标
const getCategoryIcon = (categoryId) => {
  switch (categoryId) {
    case 1:
      return 'Bell'
    case 2:
      return 'InfoFilled'
    case 3:
      return 'Promotion'
    default:
      return 'Document'
  }
}

// 根据分类ID获取标签类型
const getCategoryTagType = (categoryId) => {
  switch (categoryId) {
    case 1:
      return 'primary'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    default:
      return 'info'
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 截断文本
const truncateText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 格式化内容（将换行符转换为HTML格式）
const formatContent = (content) => {
  if (!content) return ''
  return content.replace(/\n/g, '<br>')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchAnnouncements()
})

// 在组件卸载前清理
onBeforeUnmount(() => {
  announcementDetail.value = null
})
</script>

<style scoped>
.announcement-container {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #3f51b5, #3949ab);
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
}

.page-title p {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.category-card {
  margin-bottom: 20px;
}

.category-menu {
  border-right: none;
}

.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.announcement-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.announcement-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.announcement-top {
  border-left: 4px solid #f56c6c;
}

.announcement-header {
  margin-bottom: 10px;
}

.announcement-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  display: flex;
  align-items: center;
}

.top-tag {
  margin-right: 8px;
}

.announcement-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #909399;
  font-size: 13px;
}

.announcement-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15px;
  font-size: 14px;
}

.announcement-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.read-count {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-container {
  min-height: 300px;
  padding: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.detail-publisher, .detail-date {
  color: #909399;
  font-size: 14px;
}

.detail-read-count {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 14px;
}

.detail-content {
  line-height: 1.8;
  font-size: 15px;
  color: #303133;
  margin-bottom: 20px;
}

.detail-valid-time {
  color: #909399;
  font-size: 14px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 15px;
    width: 100%;
  }
  
  .page-actions .el-input {
    width: 100% !important;
  }
  
  .announcement-meta {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .detail-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 